package cloud.seri.gateway.security.oauth2

import cloud.seri.gateway.config.oauth2.OAuth2Properties
import io.github.jhipster.config.JHipsterProperties
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.http.HttpHeaders
import org.springframework.stereotype.Component
import org.springframework.util.Base64Utils
import org.springframework.util.MultiValueMap
import org.springframework.web.client.RestTemplate

import java.nio.charset.StandardCharsets

/**
 * Client talking to UAA's token endpoint to do different OAuth2 grants.
 */
@Component
class UaaTokenEndpointClient(
    @Qualifier("loadBalancedRestTemplate") restTemplate: RestTemplate,
    jHipsterProperties: JHipsterProperties,
    oAuth2Properties: OAuth2Properties
) : OAuth2TokenEndpointClientAdapter(restTemplate, jHipsterProperties, oAuth2Properties), OAuth2TokenEndpointClient {

    /**
     * @return a Basic authorization header to be used to talk to UAA.
     */
    protected val authorizationHeader: String
        get() {
            val clientId = getClientId()
            val clientSecret = getClientSecret()
            val authorization = "$clientId:$clientSecret"
            return "Basic " + Base64Utils.encodeToString(authorization.toByteArray(StandardCharsets.UTF_8))
        }

    override fun addAuthentication(reqHeaders: HttpHeaders, formParams: MultiValueMap<String, String>) {
        reqHeaders.add("Authorization", authorizationHeader)
    }

}
